//
//  BCPutCoinQrIdentificationController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2019/1/14.
//  Copyright © 2019 guoshikeji. All rights reserved.
//

#import "BCPutCoinQrIdentificationController.h"

//
#import "BCValidateAddressRequest.h"

@interface BCPutCoinQrIdentificationController () <QMUIImagePreviewViewDelegate,QMUIZoomImageViewDelegate>

@property (nonatomic, strong) QMUIImagePreviewView *imagePreviewView;


/**
 *initRecognitionFlag
 */
@property (nonatomic, assign) BOOL initRecognitionFlag;

@end

@implementation BCPutCoinQrIdentificationController

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    self.view.backgroundColor = [UIColor blackColor];
    self.customNaviBar.backgroundColor = [self.view.backgroundColor colorWithAlphaComponent:.5];
    //
    [self setupSubviews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.navigationController) {
        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }//
    if (!self.navigationController.navigationBar.hidden) {
        [self.navigationController setNavigationBarHidden:true animated:true];
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //
    if (!self.initRecognitionFlag) {
        self.initRecognitionFlag = true;
        [self handleImage:self.qrImage];
    }
}


- (void)setupSubviews {
    self.title = BCLocalizedKey(@"Recognition QR Code");
    //
    self.imagePreviewView = [[QMUIImagePreviewView alloc] initWithFrame:self.view.bounds];
    self.imagePreviewView.delegate = self;
    [self.view addSubview:self.imagePreviewView];
    self.imagePreviewView.userInteractionEnabled = false;
}


#pragma mark - QMUIImagePreviewViewDelegate
- (NSUInteger)numberOfImagesInImagePreviewView:(QMUIImagePreviewView *)imagePreviewView {
    return 1;
}
- (void)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView renderZoomImageView:(QMUIZoomImageView *)zoomImageView atIndex:(NSUInteger)index {
    zoomImageView.image = self.qrImage;
}


#pragma mark - 开始识别图中是否有二维码
- (NSArray *)startIndentificationImageHasQrCode:(UIImage *)image {
    // CIDetector(CIDetector可用于人脸识别)进行图片解析，从而使我们可以便捷的从相册中获取到二维码
    // 声明一个 CIDetector，并设定识别类型 CIDetectorTypeQRCode
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyHigh}];
    // 取得识别结果
    CIImage *image_ci = [CIImage imageWithCGImage:image.CGImage];
    //
    NSArray *features = [detector featuresInImage:image_ci];
    //
    return features;
}

- (void)handleImage:(UIImage *)image {
    WEAK_SELF
    NSString *loading = BCLocalizedKey(@"In Recognition");
    [QMUITips showLoading:loading inView:self.view];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"%f",image.scale);
        NSArray *features = [self startIndentificationImageHasQrCode:image];
        dispatch_async(dispatch_get_main_queue(), ^{
            [QMUITips hideAllTipsInView:wself.view];
            if (features.count) {
//                if (features.count==1) {
//                    CIQRCodeFeature *feature = [features objectAtIndex:0];
//                    [wself requestValidate:feature.messageString];
//                }else {//有多个二维码
//                    [wself handleMoreFeatures:features];
//                }
//                [wself handleMoreFeatures:features];
                NSString *message;
                for (CIQRCodeFeature *obj in features) {
                    message = obj.messageString;
                }
                [self requestValidate:message];
            }else {//未识别出二维码
                [wself alertNoQrCode];
            }
        });
    });
}
//
/**
 提示未识别出二维码
 */
- (void)alertNoQrCode {
    NSString *title = BCLocalizedKey(@"Unrecognized QR Code");
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    //
    WEAK_SELF
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [wself.navigationController popViewControllerAnimated:true];
    }];
    [alert addAction:cancel];
    //
    UIAlertAction *agin = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Recognition Again") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [wself handleImage:wself.qrImage];
    }];
    [alert addAction:agin];
    [self.navigationController presentViewController:alert animated:true completion:nil];
}

//校验
- (void)requestValidate:(NSString *)address {
    [self.view bc_showActivityIndicatorBackgroundColor:[UIColor clearColor] insets:UIEdgeInsetsZero activityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    //
    BCValidateAddressRequest *request = [BCValidateAddressRequest new];
    request.addr = address;
    //
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.view bc_hiddenActivityIndicator];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCValidateAddressResponse *resp = result;
        if (resp.data.isvalid) {
            [wself completeScanningWithStringValue:request.addr];
        }else {
            [wself showErrorTitle:BCLocalizedKey(@"The address is invalid") message:request.addr];
        }
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error) {
            [wself showErrorTitle:error.domain message:request.addr];
        }
    }];
    [request requestServer];
}

- (void)showErrorTitle:(NSString *)title message:(NSString *)message {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    //
    WEAK_SELF
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [wself.navigationController popViewControllerAnimated:true];
    }];
    [alertVC addAction:cancelAction];
//    UIAlertAction *scanningAction = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Scanning Again") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [wself requestValidate:message];
//    }];
//    [alertVC addAction:scanningAction];
    //
    [self.navigationController presentViewController:alertVC animated:true completion:nil];
}

- (void)completeScanningWithStringValue:(NSString *)stringValue {
    if (stringValue.length) {
        WEAK_SELF
        NSString *title = BCLocalizedKey(@"The address is valid");
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:stringValue preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *done = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Sure") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (wself.delegate&&[wself.delegate respondsToSelector:@selector(recognitionedValidAddress:)]) {
                [wself.delegate recognitionedValidAddress:stringValue];
                [wself.navigationController popViewControllerAnimated:true];
            }
        }];
        [alertVC addAction:done];
        [self.navigationController presentViewController:alertVC animated:true completion:nil];
    }
}

@end
